package thread.day2;

/**
 * 解决多线程同步问题的方法1:同步锁
 * 将线程间数据交互的代码用synchronize关键字包裹,并加监视器(锁)
 * synchronize(监视器){
 * //代码内容
 * }
 * <p>
 * 注意:1.必须保证线程用的同一个监视器(锁)
 *
 *
 * @author wx
 * @create 2019-11-28 11:26
 */
public class SynchronizeDemo1 {
    public static void main(String[] args) {
        TicketCellThread t1 = new TicketCellThread();
        TicketCellThread t2 = new TicketCellThread();
        TicketCellThread t3 = new TicketCellThread();
        t1.setName("Windows-1");
        t2.setName("Windows-2");
        t3.setName("Windows-3");
        t1.start();
        t2.start();
        t3.start();
    }
}


class TicketCellThread extends Thread {
    public static int ticket = 100;
   static Object  lockObj = new TicketCellThread();

    @Override
    public void run() {
        while (true) {
            synchronized (lockObj) {
                //错误的方法
//                synchronized (TicketCellThread.class){
                if (ticket > 0) {
                    try {
                        sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + " ticket： " + ticket);
                    ticket--;
                } else {
                    break;
                }
            }
        }
    }
}